package com.example.demo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.base.WpsResponse;
import com.example.demo.facade.WpsDocumentFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

@RequestMapping("/wps")
@RestController("WpsCallbackController")
public class WpsCallbackController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WpsDocumentFacade wpsDocumentFacade ;


    /**
     * 文件格式转换回调
     *  本API需与 https://dhs.open.wps.cn/pre/v1/convert  的参数CallBack 访问地址一致
     *  调用https://dhs.open.wps.cn/pre/v1/convert后，根据CallBack参数回调到该地址处理转换执行结果
     * 从Body中取得json数据，包括Code、TaskId
     * 如果Code=OK，则根据TaskId调https://dhs.open.wps.cn/pre/v1/query接口，取得转换结果
     */
    @RequestMapping(value = "/convertresult",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Object> convertresult(HttpServletRequest request){
        try {
            BufferedReader buf = request.getReader();
            String str, data = "";
            while((str = buf.readLine()) != null){
                data += str;
            }
            logger.info("convertresult取得data={}" , data);

            if (!StringUtils.isEmpty(data)){
                JSONObject dataJson = JSON.parseObject(data);
                logger.info("convertresult取得Code={}，TaskId={} ，dataJson={}" , dataJson.get("Code") , dataJson.get("TaskId") , dataJson.toJSONString());

                //检查结果
                if (dataJson.get("TaskId") != null){
                    String taskId = (String)dataJson.get("TaskId");
                    String url = wpsDocumentFacade.recordWPSConvertResult(taskId) ;
                    if (!StringUtils.isEmpty(url)){
                        logger.warn("convertresult回调取不到转换结果，taskId={}" , taskId);
                    }
                }
            }


            return WpsResponse.success("ok");
        }catch (Exception e){
            return WpsResponse.bad("fail");
        }
    }

    /**
     * 文件转换
     */
    @RequestMapping(value = "/fileconvert",method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Object> fileconvert(String taskId , String srcUri , String fileName , String exportType) {
        wpsDocumentFacade.fileConvert(taskId , srcUri , fileName , exportType) ;
        return WpsResponse.success("ok");
    }


    /**
     * 查询文件转换结果
     * http://122.224.255.42:3393/wps/queryfileconvert?taskId=abcd1234
     */
    @RequestMapping(value = "/queryfileconvert",method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Object> queryfileconvert(String taskId ) {
        String url = wpsDocumentFacade.recordWPSConvertResult(taskId) ;
        return WpsResponse.success(url);
    }


}
